<template>
	<view class="content-box">
		<scroll-view scroll-y="true" class="scroll-Y">
			<view class="suggest-one">
				<view>故障现象</view>
				<view class="suggest-content p10">{{ propDetail.content }}</view>
				<hr>
				<view>处置流程</view>
				<view class="image_box">
					<u-button class="active" size='mini' v-if='true||leaderId==getUserId()'
						@tap="handleClick">处置流程</u-button>
					<!-- 		<image width="100vw" :src="processurl" :data-src="processurl" mode="aspectFit">
					</image>
					<previewImage ref="previewImage" :imgs="imgList"></previewImage> -->
				</view>
			</view>
			<hr>
			<view class="suggest">

				<view class="title">维修建议</view>
				<view v-if="false&&suggestValue" class="suggest-textarea">
					<u-input type="textarea" disabled placeholder-style="color:#9d9d9d;" v-model="suggestValue"
						placeholder="" />
				</view>
				<!-- <view v-else class="suggest-textarea">
					<text>{{ suggestValue }}</text>
				</view> -->
			</view>
			<hr>
			<view class="suggest-two">

				<view>
					<text>处置结果</text>
				</view>
				<view class="suggest-content">
					<!-- 	<text class="blod">检测方法:</text>
					{{ armDetail.method? "\n"+armDetail.method:'' }} -->
				</view>
				<!-- <text class="reason blod">可能原因:</text> -->
				<view v-if="!httpParams.routefrom || httpParams.routefrom != 'maHistory'" class="filed">
					<u-input placeholder='请输入处置结果' :disabled="leaderId!=getUserId()" v-model="armDetail.reason"
						type="textarea" />
					<u-button class="active" :disabled="leaderId!=getUserId()" size="mini"
						@click="checkReson">选择</u-button>
				</view>
				<view v-else>
					<text>
						{{ armDetail.reason }}
					</text>
				</view>
				<hr>
				<view class="imgTitle title">上传图片</view>
				<view class="upView"
					v-if="leaderId==getUserId()&&!meanwhileUploadFlag && (!httpParams.routefrom || httpParams.routefrom != 'maHistory')">
					<htz-image-upload ref="uploadchild" :max="4" :mediaType='uploadMediaType' :formData='uploadformData'
						v-model="uploadData" :uploadSuccess="uploadSuccess" @imgDelete='imgDeleteCallback'
						:action="uploadUrl">
					</htz-image-upload>
				</view>
				<view
					v-else-if=" leaderId==getUserId()&&meanwhileUploadFlag && (!httpParams.routefrom || httpParams.routefrom != 'maHistory')"
					class="photo-upload">
					<view v-for="(item, index) in simpleImageList" :key="index">
						<image :src="item" @click="imgPreview(index,simpleImageList)"></image>
					</view>
				</view>
				<view v-else class="photo-upload">
					<view v-for="(item, index) in uploadData" :key="index">
						<u-image width="70px" height="70px" :src="item" @click="imgPreview(index,uploadData)"></u-image>
					</view>
				</view>
			</view>
		</scroll-view>
		<view v-if="leaderId==getUserId()&&(!httpParams.routefrom || httpParams.routefrom != 'maHistory')"
			class="suggest-button">
			<!-- <button :class="[btn1 ? 'active' : 'inactive']">语音</button> -->
			<!-- <u-button size="medium" @click="uploadButton('image')" :class="[btn2 ? 'active' : 'inactive']">图片</u-button> -->
			<!-- <button @click="uploadButton('video')" :class="[btn3 ? 'active' : 'inactive']">视频</button> -->
			<u-button size="medium" 
				@click="meanwhileUploadFlag ? meanwhileSubmit() : submit()"
				:class="[btn4 ? 'active' : 'inactive']">提交</u-button>
		</view>
		<u-select v-model="show_picker" :list="columns" :label-name="'reason'" :value-name="'reason'"
			@confirm="onConfirm" @cancel="onCancel">
		</u-select>
	</view>
</template>
<script>
	import {
		WORK_CONTROLLER
	} from "../../api/pms";
	import htzImageUpload from '@/components/htz-image-upload/htz-image-upload.vue'
	import previewImage from '@/components/kxj-previewImage/kxj-previewImage.vue';
	export default {
		name: "maintenSuggest",
		components: {
			htzImageUpload,
			previewImage
		},
		props: ["httpParams"],
		data() {
			return {
				meanwhileUploadFlag: false, // true 同时上传方式  false 分开上传方式
				uploadData: [],
				uploadUrl: '',
				uploadMediaType: "image",
				uploadformData: {},
				suggestValue: "",
				btn1: false,
				btn2: true,
				btn3: false,
				btn4: true,
				processurl: "/static/img/emergency/01fault.png",
				armDetail: {},
				propDetail: {},
				faultAdviceId: "",
				simpleImageList: [],
				imgList: [],
				x: 0,
				y: 0,
				scale: 1,
				show: false,
				woSn: '',
				leaderId: "",
				columns: [],
				show_picker: false,
				armcode: ''
			};
		},

		created() {
			this.uploadUrl = this.$store.state.baseEmerUrl + '/emergency/adviceDataAdd'

			this.initDetail();
			this.initDetail2();
			this.getWon()
			console.log('httpParams', this.httpParams)
			// this.getImgUrlList();
		},
		methods: {
			async checkReson() {
				await this.initDetail2('query');
				this.show_picker = true
			},
			onConfirm(item) {
				console.log('item', item)
				this.armDetail.reason = item[0].label
				let filterArr = this.columns.filter(filitem => filitem.reason = item[0].label)
				this.armDetail = filterArr[0]
				// this.armDetail.woLine = item[0].value
			},
			onCancel() {
				this.show_picker = false
			},
			// 根据应急查询对应的工单
			async getWon() {
				let params = {
					emergencyId: this.httpParams.faultId,
					pageNum: 1,
					pageSize: 10
				};
				await this.fetch('get', this.$store.state.baseUrl + WORK_CONTROLLER.GET_ALL_WORKORDER_LIST, params,
						true)
					.then((res) => {
						if (res.success && res.data && res.data.content && res.data.content.length) {
							this.woSn = res.data.content[0].woSn
							this.leaderId = res.data.content[0].woLeaderId
							this.woState = res.data.content[0].woState
						} else {
							console.error(res)
						}
					})
			},
			// 结束检修 对应的抢修工单状态流转
			async endCheck() {
				// 工单结束检修
				if (this.woState == '进行中') {
					await this.fetch("post", this.$store.state.baseUrl + WORK_CONTROLLER.POST_End, {
						woSn: this.woSn
					}, false).then((res) => {
						if (res.code == 101200999) {
							uni.showModal({
								title: "卡控信息",
								content: res.message + '，请进行复检',
								showCancel: false,
							})
						} 
						if(res.success){
							// 提交工单
							 this.fetch("post", this.$store.state.baseUrl + `/api/work/task/submit`, {
								woSn: this.woSn,
							}).then((res) => {
								if(res.success){
									uni.showToast({
										title: "工单提交成功",
										icon: "none",
									});
									this.orderRece()
								}
							this.getWon()
							  
							});
						}
					});
				}
			
			},
			handleClick(e) {
				uni.navigateTo({
					url: "/pages/emergency/flow?faultId=" + this.httpParams.faultId + "&armCode=" + this.httpParams
						.armcode + "&routefrom=" + this.httpParams.routefrom
				});
				return
				var param = e.currentTarget.dataset.src;
				this.$refs.previewImage.open(0); // 传入当前选中的图片地址或序号
				return; //如需测试和uni原生预览差别可注释这两行

			},
			initDetail() {
				let params = {
					faultId: this.httpParams.faultId,
					// personId: this.getUserId()
				}
				this.fetch('POST', this.$store.state.baseEmerUrl + '/emergency/adviceDataList', params, false).then((
					res) => {
					if (res.success) {
						if (res.data && res.data[0]) {
							this.faultAdviceId = res.data[0].idK || '';
							this.suggestValue = res.data[0].advice || '';
							let imgUrlIdList = res.data[0].dataIds ? res.data[0].dataIds.split(",") : '';
							this.uploadData = imgUrlIdList ? imgUrlIdList.map(item => this.$store.state
								.baseEmerUrl +
								'/emergency/adviceDataPreview?id=' + item) : [];
						}

						this.uploadformData = {
							faultAdviceId: this.faultAdviceId,
							faultId: this.httpParams.faultId,
							personId: this.getUserId()
						}

					} else {
						console.error(res)
					}
				})
			},
			async initDetail2(param) {
				this.propDetail = {
					content: this.httpParams.content
				}
				let armCode = this.httpParams.armcode
				await this.fetch('GET', this.$store.state.baseEmerUrl + '/emergency/fault-dic/' + armCode, {}, true)
					.then((
						res) => {
						if (res.returnCode == "2004" && res.data) {
							if (res.data.pictureId) {
								let pictureId = res.data.pictureId
								if (pictureId == "01fault.png") {
									this.processurl = "/static/img/emergency/01fault.png"

								} else {
									this.processurl = "/static/img/emergency/" + pictureId
								}
								let url = this.processurl.replace('.png', '1.png')
								this.imgList = [url]
							}

							if (res.data.list && res.data.list.length != 0) {
								if (!param) {
									this.armDetail = res.data.list[0]
								}
								this.columns = res.data.list
							}
						} else {
							console.error(res)
						}
					})
			},
			// getImgUrlList() {
			// 	let params = {
			// 		faultId: this.httpParams.faultId,
			// 		personId: this.getUserId()
			// 	}
			// 	this.fetch('POST', this.$store.state.baseEmerUrl + '/emergency/adviceDataList', params,
			// 		false).then((
			// 		res) => {
			// 		if (res.returnCode == "2004" && res.data && res.data[0]) {
			// 		let imgUrlIdList = res.data[0].dataIds ? res.data[0].dataIds.split(",") : '';
			// 		this.uploadData = imgUrlIdList ? imgUrlIdList.map(item => this.$store.state.baseEmerUrl +
			// 			'/emergency/adviceDataPreview?id=' + item) : [];
			// 		}
			// 	})
			// },
			imgPreview(index, images) {
				uni.previewImage({
					urls: images,
					current: index,
					loop: true,
				});
			},
			simpleUploadImage() {
				if (this.btn2) {
					uni.chooseImage({
						success: (chooseImageRes) => {
							const tempFilePaths = chooseImageRes.tempFilePaths;
							this.simpleImageList.push(tempFilePaths[0]);
						}
					});
				}
			},
			// uploadButton(option) {
			// 	if (option == 'image') {
			// 		if (this.btn2) {
			// 			if (!this.meanwhileUploadFlag) {
			// 				this.$refs.uploadchild.parentClick('image')
			// 			} else {
			// 				this.simpleUploadImage()
			// 			}
			// 		}
			// 	} else if (option == 'video') {
			// 		if (this.btn3) {
			// 			this.$refs.uploadchild.parentClick('video')
			// 		}
			// 	} else {
			// 		console.error(option)
			// 	}
			// },
			uploadSuccess(res) {
				if (res.statusCode == 200 && res.data) {
					let photoID = JSON.parse(res.data).data.fileId;
					let url = this.$store.state.baseEmerUrl + '/emergency/adviceDataPreview?id=' + photoID
					this.faultAdviceId = JSON.parse(res.data).data.faultAdviceId
					this.uploadformData = {
						faultAdviceId: this.faultAdviceId,
						faultId: this.httpParams.faultId,
						personId: this.getUserId()
					}
					console.log('uploadData', this.uploadData)
					return {
						success: true,
						url
					}
				} else {
					return {
						success: false,
						url: ''
					}
				}
			},
			imgDeleteCallback({
				del: del,
				tempFilePaths: tempFilePaths
			}) {
				let photoID = del.split("id=")[1];
				this.deleteFile(photoID)
			},
			deleteFile(fileID) {
				this.fetch('POST', this.$store.state.baseEmerUrl + `/emergency/deleteAdviceData/${fileID}`, {}, false)
					.then((
						res) => {
						if (res.data == '"success"') {
							console.log("该图片删除成功！");
						}
					})
			},
			meanwhileSubmit() {
				// if (!this.suggestValue) {
				// 	uni.showToast({
				// 		title: '请先输入维修建议！',
				// 		icon: 'none'
				// 	})
				// 	return;
				// }
				const uploadTask = uni.uploadFile({
					url: this.$store.state.baseEmerUrl + '/emergency/adviceAndDataSaveOrUpdate',
					// filePath: tempFilePaths[0],
					// name: 'file',
					files: this.simpleImageList.map((value, index) => {
						return {
							name: "files",
							uri: value
						}
					}),
					formData: {
						idK: this.faultAdviceId,
						faultId: this.httpParams.faultId,
						personId: this.getUserId(),
						advice: this.suggestValue
					},
					success: (uploadFileRes) => {
						// console.log("上传成功回调函数：", uploadFileRes.data);

						if (JSON.parse(uploadFileRes.data).data == 'success') {
							uni.showToast({
								title: '提交成功！',
								icon: 'none'
							})
						} else {
							console.error(res)
						}
					}
				});

				// uploadTask.onProgressUpdate((res) => {
				// 	console.log('上传进度' + res.progress);
				// 	console.log('已经上传的数据长度' + res.totalBytesSent);
				// 	console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

				// 	// 测试条件，取消上传任务。
				// 	if (res.progress > 50) {
				// 		console.log("执行取消上传任务测试");
				// 		// uploadTask.abort();
				// 	}
				// });
			},
			async submit() {
				console.log('this---', this.uploadData)
				// if (!this.suggestValue) {
				// 	uni.showToast({
				// 		title: '请先输入维修建议！',
				// 		icon: 'none'
				// 	})
				// 	return;
				// }
				let params = {
					idK: this.faultAdviceId,
					faultId: this.httpParams.faultId,
					personId: this.getUserId(),
					advice: this.suggestValue,
					reason: this.armDetail.reason
				}

				await this.fetch('POST', this.$store.state.baseEmerUrl + '/emergency/adviceSaveOrUpdate', params,
					false).then((
					res) => {
					if (res.success && res.data == "success") {
						uni.showToast({
							title: '提交成功！',
							icon: 'none'
						})
					} else {
						console.error(res)
					}
				})
				//  点击提交时，同时调用 结束检修 改变工单状态
				await this.endCheck()
			},

			//   将流程变成待审核
			orderRece() {
				let processCode = 7
				let potoId = this.uploadData.map(item => {
					let value = item.split("=")[1]
					return value
				})
				let contentJson = JSON.stringify([{
					name: this.$store.state.userInfo.name,
					id: this.getUserId(),
					phone: this.$store.state.userInfo.tel,
					roleName: (this.$store.state.userInfo.roles||[]).map(role => role.name).join(","),
					reason: this.armDetail.reason,
					potoId: potoId.toString(),
					advice: this.suggestValue,
				}])
				let emergencyTPersonList = [{
					faultId: this.httpParams.faultId,
					personId: this.getUserId(),
				}]

				let params = {
					processCode,
					faultId: this.httpParams.faultId || '',
					emergencyTPersonList,
					contentJson,

				};
				this.fetch('PUT', this.$store.state.baseEmerUrl + '/emergency/faultAction', params, false).then((
					res) => {})
			}

		}
	}
</script>

<style scoped lang="less">
	.imgTitle {
		padding-bottom: 0px !important;
		margin: 0px !important;
		padding-left: 20px !important;
		color: #64d3ca !important;
	}

	.scroll-Y {
		flex: 1;
		height: 0;
		margin-bottom: 10px;
	}

	.title {
		color: #64d3ca;
		font-weight: bold;
		font-size: 30upx;
		padding: 15px 0px 10px 0px;
	}

	.blod {
		font-weight: 600;
	}

	.reason {
		padding-left: 20px;
	}

	.content-box {
		// position: relative;
		display: flex;
		flex-direction: column;
		padding-bottom: 0px;
		height: calc(100% - 125px) !important;
		background-color: #ffffff;
	}

	hr {
		border: 0;
		border-top: 2px solid #f1f1f1;
	}

	.p10 {
		padding: 0 20upx 10px 40upx;
	}

	.suggest {
		padding: 0 20px;
	}

	.suggest-content {}

	.suggest-one {
		padding-bottom: 10px;
		// margin-top: 40upx;
		// height: 460upx;
		background-color: #ffffff;

		view:nth-child(1) {
			font-weight: bold;
			color: #64d3ca;
			font-size: 30upx;
			margin-left: 40upx;
			padding-top: 30upx;
			margin-bottom: 20upx;
		}

		view:nth-child(4) {
			font-weight: bold;
			color: #64d3ca;
			font-size: 30upx;
			margin-left: 40upx;
			margin-top: 20upx;
			margin-bottom: 20upx;
		}

		view:nth-child(5) {
			// margin-left: 80upx;
		}
	}

	.suggest-two {
		margin-top: 14upx;
		// height: 1050upx;
		background-color: #ffffff;

		view {
			margin-left: 40upx;
		}

		view:nth-child(1) {
			padding-top: 30upx;
			margin-bottom: 20upx;

			text:nth-child(1) {
				color: #64d3ca;
				font-weight: bold;
				font-size: 30upx;
			}

			text:nth-child(2) {
				float: right;
				color: #e2e2e2;
				font-size: 28upx;
				margin-right: 30upx;
			}

		}

		view:nth-child(2) {
			// font-weight: bold;
			// color: black;
			font-size: 28upx;
			margin-bottom: 10upx;
			padding-right: 10px;
			white-space: pre-wrap;
		}

		view:nth-child(3) {
			color: #adadad;
			font-size: 31upx;
			margin-bottom: 10upx;
		}

		view:nth-child(5) {
			color: #adadad;
			font-size: 31upx;
			margin-top: 10upx;
			margin-bottom: 10upx;
		}

		.suggest-textarea {
			margin: 20upx 40upx 10upx 40upx;

			textarea {
				height: 220upx;
				width: 100%;
			}
		}

		.photo-upload {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			justify-content: space-evenly;
			align-items: stretch;
			// padding-right: 44upx;
			margin-left: 0px;

			>view:nth-child(1) {
				view {
					margin-left: 0px;
				}
			}

			view {
				margin-left: 0px;
				padding-right: 0px;

				image {
					width: 200upx;
					height: 200upx;
				}
			}

			>view {
				padding-top: 0px;
				margin-bottom: 0px;
				// margin-left: 12vw;

				>view {
					padding-top: 10px;
					margin-left: 10px;
				}
			}
		}
	}

	.suggest-button {
		// position: fixed;
		z-index: 999;
		bottom: 0;
		width: 100%;
		// height: 100upx;
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: space-evenly;
		align-items: center;
		background-color: skyblue;
		padding: 10px 10upx 10px;
		background-color: #ffffff;
		border-top: 1px solid #f0f0f0;
		box-shadow: -2px -2px 4px #f0f0f0;

		button {
			// width: 162upx;
			// height: 80upx;
			color: black;
			font-size: 28upx;
			font-weight: bolder;
			line-height: 80upx;
		}

		.active {
			background-color: #14c2a7;
			color: white;
		}

		.inactive {
			background-color: #f3f3f3;
		}
	}

	.active {
		background-color: #14c2a7;
		color: white;
	}

	.image_box {
		margin: 5px 10px 0;
		text-align: right;
	}

	/deep/.filed {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding-right: 10px;

		.u-input {
			margin-right: 10px;
			margin-left: 0px;
		}
	}

	.upView {
		margin-bottom: 20px;
	}

	/deep/ .content {
		padding-bottom: 0px !important;
	}
</style>
<style>
	.filed .u-label {
		width: 0px !important;
		flex: 0 0 0px;
	}
</style>